//
//  OMDeliveryAddressViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/23.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMDeliveryAddressViewController.h"
#import "OMDeliveryAddressTableCell.h"
#import "OMDeliveryAddressModifyViewController.h"
#import "OMDeliveryInfo.h"
#import "OMDeliveryAddressSelectionTableCell.h"

NSString *const OMDELIVERY_ADDRESS_DELETE_NOTIFICATION = @"OMDELIVERY_ADDRESS_DELETE_NOTIFICATION_KEY";
@interface OMDeliveryAddressViewController () <OMDeliveryAddressTableCellDelegate>
@property (nonatomic, strong) UIButton * confirmButton;
@property (nonatomic, assign) NSUInteger selectedIndex;
@property (nonatomic, strong) NSMutableArray <OMDeliveryInfo *>*deliveryInfos;
@end

@implementation OMDeliveryAddressViewController


- (void)viewDidLoad {

    [self.tableView registerClass:[OMDeliveryAddressTableCell class] forCellReuseIdentifier:[OMDeliveryAddressTableCell cellIdentifier]];
    [self.tableView registerClass:[OMDeliveryAddressSelectionTableCell class] forCellReuseIdentifier:[OMDeliveryAddressSelectionTableCell cellIdentifier]];

    [super viewDidLoad];

    self.title = self.delegate?@"选择收货地址":@"我的地址";
    self.emptyImage = [UIImage imageNamed:@"dizi"];
    self.emptyDataMessage = @"您还没有添加地址";
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(@(64));
    }];


    UIView *footer = [UIView new];
    footer.backgroundColor = SM_whiteColor;
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.height.equalTo(@(SM_SIZE(130)));
        make.left.right.bottom.equalTo(@0);
    }];
    [footer addSubview:self.confirmButton];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(SM_SIZE(20)));
        make.right.bottom.equalTo(@(SM_SIZE(-20)));
    }];
    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [footer addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@(.5f));
    }];

    [self startAnimating:YES];
    [self getAddressList];

    [self observeSetup];

}

- (void)observeSetup
{
    @weakify(self);
    [SMNotificationMonitorRACSignal(OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION) subscribeNext:^(id x) {
        @strongify(self);
        [self getAddressList];
    }];

    [SMNotificationMonitorRACSignal(OM_NOTIFICATION_KEY_LOGIN_SUCCESS) subscribeNext:^(id x) {
        @strongify(self);
        [self startAnimating:true];
        [self getAddressList];
    }];
}

- (void)reloadDataFromNetWork
{
    [self getAddressList];
}

- (void)getAddressList
{

    [KTHttpUtils GET:@"receiver/list.jhtml"
          parameters:nil
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
              if (isSuccess) {
                  [self startAnimating:NO];
                  self.deliveryInfos = [[OMDeliveryInfo mj_objectArrayWithKeyValuesArray:responseObject[OMDataKey]] mutableCopy];
                  [self.tableView reloadData];
              }else {
                  [self showNetWorkError];
                  [OMHUD HUDError:message];
              }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - table view delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.deliveryInfos.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//    if (self.delegate) {
//        OMDeliveryAddressSelectionTableCell *cell = [OMDeliveryAddressSelectionTableCell tableViewCellWithTableView:self.tableView];
//        [cell configureCellWithObj:self.deliveryInfos[indexPath.row]];
//        return cell;
//    }
    OMDeliveryAddressTableCell *cell = [OMDeliveryAddressTableCell tableViewCellWithTableView:tableView];
    [cell configureCellWithObj:self.deliveryInfos[indexPath.row]];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [tableView fd_heightForCellWithIdentifier:[OMDeliveryAddressTableCell cellIdentifier] cacheByIndexPath:indexPath configuration:^(OMDeliveryBaseAddressTableCell* cell) {
        [cell configureCellWithObj:self.deliveryInfos[indexPath.row]];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (self.delegate && [self.delegate respondsToSelector:@selector(didSelectDeliveryInfo:)]) {
        [self.delegate didSelectDeliveryInfo:self.deliveryInfos[indexPath.row]];
        [self backAction];
    }
}

#pragma mark - OMDeliveryAddressTableCellDelegate
- (void)didSelectDefaultBtnAtIndexPath:(NSIndexPath *)indexPath
{
    [self setDefaultAddressAtIndex:indexPath.row];
}

- (void)didClickEditButtonAtIndexPath:(NSIndexPath *)indexPath
{
    NaviPush(@"OMDeliveryAddressModifyViewController", (@{@"isModifying":@(YES),@"info":self.deliveryInfos[indexPath.row]}));
}

- (void)didClickDeleteButtonAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self);
    [KTAlertView alertWithMessage:@"确认要删除这个地址吗?" Title:@"提示" ButtonTitles:@[@"删除"] withClickBlock:^(NSUInteger indexOfButton) {
        if (indexOfButton) {
            @strongify(self);
            [self deleteAddressAtIndex:indexPath.row];
        }
    }];
}

//删除地址
- (void)deleteAddressAtIndex:(NSUInteger)index
{
    [OMHUD HUDLoading:nil];
    OMDeliveryInfo *info = self.deliveryInfos[index];
    [KTHttpUtils POST:@"receiver/delete.jhtml"
           parameters:@{@"id":info.id}
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {
               if (isSuccess) {
                   [OMHUD HUDHide];
                   [self.deliveryInfos removeObjectAtIndex:index];
                   [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]]
                                         withRowAnimation:UITableViewRowAnimationNone];
                   SMNotificationPost(OMDELIVERY_ADDRESS_DELETE_NOTIFICATION, nil);
               }else {
                   [OMHUD HUDError:message];
               }
    }];
}

//设置地址为默认
- (void)setDefaultAddressAtIndex:(NSUInteger)index
{
    OMDeliveryInfo *info = self.deliveryInfos[index];
    if (info.isDefault) {
        return;
    }
    [OMHUD HUDShieldLoading:nil];
    [KTHttpUtils POST:@"receiver/update.jhtml"
           parameters:@{
                        @"receiver.area_id":info.areaId,
                        @"receiver.address":info.address,
                        @"receiver.consignee":info.consignee,
                        @"receiver.phone":info.phone,
                        @"receiver.id":info.id,
                        @"receiver.is_default":@(YES),
                        }
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {
               if (isSuccess) {
                   [OMHUD HUDHide];
                   SMNotificationPost(OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION, nil);
               }else {
                   [OMHUD HUDError:message];
               }
           }];
}




#pragma mark - Getters
- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton new];
        [_confirmButton setTitle:@"添加地址" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:RGBACOLOR(0, 0, 0, .26)] forState:UIControlStateDisabled];
        _confirmButton.titleLabel.font = SM_CFont(35);
        [_confirmButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.layer.cornerRadius = 4.f;
        _confirmButton.clipsToBounds = true;

    }
    return _confirmButton;
}

#pragma mark - Actions
- (void)submitAction:(UIButton*)button
{
    NaviPush(@"OMDeliveryAddressModifyViewController", @{@"isModifying":@(NO)});
}
@end
